package cn.uniqueww.controller;


import cn.uniqueww.dto.DishDto;
import cn.uniqueww.entity.Category;
import cn.uniqueww.entity.DishFlavor;
import cn.uniqueww.service.CategoryService;
import cn.uniqueww.service.DishFlavorService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;;
import com.baomidou.mybatisplus.extension.api.ApiController;
import cn.uniqueww.common.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.uniqueww.entity.Dish;
import cn.uniqueww.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理(Dish)表控制层
 *
 * @author 罗玉新
 * @since 2022-09-14 12:39:58
 */
@Slf4j
@RestController
@Api(tags = "菜品管理(Dish)")
@RequestMapping("/dish")
public class DishController extends ApiController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private DishFlavorService dishFlavorService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 服务对象
     */
    @Resource
    private DishService dishService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param name 查询实体
     * @return 所有数据
     */
    @GetMapping("/page")
    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页数"),
            @ApiImplicitParam(name = "pageSize",value = "每页显示条数"),
            @ApiImplicitParam(name = "name",value = "菜品名称")
    })
    public Result page(int page, int pageSize, String name) {
        //构造分页对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();

        //构造查询器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        //查询条件封装
        queryWrapper.like(name != null, Dish::getName, name);

        dishService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        //数据清洗
            List<Dish> records = pageInfo.getRecords();
            List<DishDto> newRecords = records.stream().map(s -> {
            //创建接收对象
            DishDto dishDto = new DishDto();
            //将数据拷贝过去
            BeanUtils.copyProperties(s, dishDto);
            Long categoryId = s.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //防止空指针
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(newRecords);
        return Result.success(dtoPage);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键查询单条数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "菜品id"),
    })
    @GetMapping("{id}")
    public Result selectOne(@PathVariable Serializable id) {

        DishDto dishDto = dishService.getWithFlavors(id);
        List<DishFlavor> list = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, id));
        dishDto.setFlavors(list);
        return Result.success(dishDto);
    }


    /**
     * 查询套餐内的菜品
     *
     * @Cacheable  先查询缓存中是否有该key数据，没有则查数据将返回值放入缓存中
     * @return list数据
     */
    @ApiOperation("查询套餐内的菜品")
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "'dish_'+#dish.categoryId+'_'+#dish.status")
    public Result list(Dish dish) {
        List<DishDto>  dishDtos;
        //先从缓存中查取
//        String key  = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        //有数据则直接返回
//        if (dishDtos!=null){
//            return Result.success(dishDtos);
//        }
        List<Dish> dishList = dishService.getDishList(dish);

        dishDtos = dishList.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getId,item.getCategoryId());
            Category one = categoryService.getOne(wrapper);
            if (one!=null){
                dishDto.setCategoryName(one.getName());
            }
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list);
            return dishDto;
        }).collect(Collectors.toList());
        //存入缓存中
//        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return Result.success(dishDtos);
    }


    /**
     * 新增数据
     *
     * @param dishDto 实体对象
     * @CacheEvict  清理缓存中数据 allEntries = true表示清除该组所有数据
     * @return 新增结果
     */
    @ApiOperation("新增数据")
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public Result insert(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        //更新数据时及时清理缓存
        /*Set keys = redisTemplate.keys("dish_" + dishDto.getCategoryId() + "*");
        redisTemplate.delete(keys);*/

        dishService.saveWithFlavors(dishDto);
        return Result.success("添加成功");
    }

    /**
     * 修改数据
     *
     * @param dishDto 实体对象
     * @return 修改结果
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public Result update(@RequestBody DishDto dishDto) {
        //更新数据时及时清理缓存
//        Set keys = redisTemplate.keys("dish_" + dishDto.getCategoryId() + "*");
//        redisTemplate.delete(keys);
        dishService.upWithFlavors(dishDto);
        return Result.success("修改成功");
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete(@RequestParam("idList") List<Long> idList) {


        return Result.success(this.dishService.removeByIds(idList));
    }
}

